const db = require("../server/db.js");
const axios = require("axios");
const { appId, appSecret, getOpenidUrl } = require("./../config/wechat.js");
const User = require('./../models/user');

module.exports = {
  async getWechatSession(code) {
    try {
      const url = `${getOpenidUrl}?appid=${appId}&secret=${appSecret}&js_code=${code}&grant_type=authorization_code`;
      const response = await axios.get(url);
      if (response.data.errcode) {
        throw new Error(`微信接口错误: ${response.data.errmsg}`);
      }

      return {
        openid: response.data.openid,
        sessionKey: response.data.session_key,
        unionid: response.data.unionid || null,
      };
    } catch (error) {
      throw new Error(`获取微信openid失败: ${error.message}`);
    }
  },
  // 获取购物车列表
  async getUserInfo(userId) {
    try {
      const [rows] = await db.query(
        `
      SELECT 
        c.id as cart_id,
        c.quantity,
        c.selected,
        p.id as product_id,
        p.name,
        p.price,
        p.image,
        p.stock
      FROM cart c
      JOIN products p ON c.product_id = p.id
      WHERE c.user_id = ? AND p.status = 1
    `,
        [userId]
      );

      return rows;
    } catch (error) {
      return error;
    } finally {
      connection.release();
      console.log("数据库连接已释放");
    }
  },
};
